﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using JHStock.Update;
using Newtonsoft.Json;
using System.Threading;
using Tools;
using System.Text.RegularExpressions;
using System.Reflection;

namespace JHStock.UserForm
{
    class DealClass
    {
        private JHConfig _jhcfg;
        private Stocks _stocks;
        private Form1 form1;
        private bool _isrunning;
        private Button _completebtn;
        public ShowDeleGate ShowMsg;
        public DealClass(JHConfig _jhcfg, Stocks _stocks, Form1 form1)
        {
            this._jhcfg = _jhcfg;
            this._stocks = _stocks;
            this.form1 = form1;
            ShowMsg = form1.ThreadShowMsg;
        }
        public void TestDownLoads(System.Windows.Forms.Button btn)
        {
            //DownLoadsAllKdata(btn);
            //ConstructCQ();
            LoadFHSG();

        }
        private void LoadFHSG() //insertinto mdb
        {
            StringBuilder errormsg = new StringBuilder();
            string template = @"insert into [Kbouns](
stockid,  PDate,   SG,   ZZ,  PX, progress,CQDate, DJDate,SSDate) 
Values( [stockid],  [PDate],   [SG],   [ZZ],  [PX], '实施',[CQDate], '[DJDate]','[SSDate]');";
            List<Fhsgs> ls = JsonConvert.DeserializeObject<List<Fhsgs>>(File.ReadAllText(WorkPath + "AllFin.Dat"));
            List<string> lss1 = ls.Select(r1 =>
            {
                StringBuilder sb = new StringBuilder();
                //10派0.125元送0.5股转9.5股
                Regex re = new Regex("10派([0-9.]*)元(送([0-9.]*)股)?(转([0-9.]*)股)?");
                Stock s = _stocks.StockByNumCode(r1.stockcode.Substring(2));
                string t1 = template.Replace("[stockid]", s.ID.ToString());
                List<string> lss2 = r1.FHSG.Select(r2 =>
                {
                    string t2 = t1.Replace("[PDate]", r2.nd)
                        .Replace("[CQDate]", r2.cqr.Replace("-",""))
                        .Replace("[DJDate]", r2.djr)
                        .Replace("[SSDate]", "-");
                    string PX = "0";
                    string SG = "0";
                    string ZZ = "0";
                    Match m = re.Match(r2.FHcontent);
                    if (m.Success)
                    {
                        PX = m.Groups[1].Value;
                        if (m.Groups[3].Success)
                           SG = m.Groups[3].Value;
                        if (m.Groups[5].Success)
                            ZZ = m.Groups[5].Value;
                    }
                    t2 = t2.Replace("[PX]", PX).Replace("[SG]", SG).Replace("[ZZ]", ZZ);
                    try
                    {
                        this._stocks.Db.update(t2);
                    }
                    catch
                    {
                        errormsg.AppendLine(t2);
                    }
                    return t2;
                }).ToList();
                
                sb.Append(  string.Join("\r\n",lss2));
                return sb.ToString();
            }).ToList();
            
            MFile.WriteAllText(WorkPath + "Test.Dat",string.Join("\r\n===========\r\n",lss1));
            if(errormsg.Length>0)
            MFile.WriteAllText(WorkPath + "TestErr.Dat",string.Join("\r\n===========\r\n",errormsg.ToString()));
            
        }
        private void ConstructCQ() //From.Each.StockFile
        {
            string undeal = "";
            StringBuilder sb = new StringBuilder();
            int count = 0;
            foreach (Stock s in _stocks.stocks)
            {

                string filetemplate = "{\"stockcode\":\"[stockcode]\"\r\n,FHSG:[[value]]}";
                string path = WorkPath + "\\AllKdata\\" + s.Code + ".txt";

                if (File.Exists(path))
                {
                    string txt = File.ReadAllText(path);
                    txt = CutJsonStringHead(txt);
                    string ss = ConstructKdata(s.Code, txt);

                    filetemplate = filetemplate.Replace("[stockcode]", s.Code)
                        .Replace("[value]", ss);
                    sb.Append(filetemplate);
                    sb.AppendLine(",");
                }
                else
                {
                    undeal += s.Code + "\t";
                }
                if (count++ % 50 == 0)
                    form1.showfiletxt("已完成" + count + "/" + _stocks.stocks.Count + "中");
            }
            string path2 = WorkPath + "\\AllFin.dat";
            MFile.WriteAllText(path2, "[" + sb.ToString() + "]");
            if (undeal != "")
                MessageBox.Show(undeal);
            form1.showfiletxt("已保存文件到" + path2 + "中");
        }
        private string ConstructKdata(string stockcode, string txt)
        {
            QQStocks qs = JsonConvert.DeserializeObject<QQStocks>(txt);
            List<string> kd = qs.data[stockcode.ToLower()].day
                .Where(r1 => r1.Count == 7)
               .Select(r2 => r2[6].ToString()).ToList();
            return string.Join(",\r\n", kd);
        }
        private string CutJsonStringHead(string txt)
        {
            if (txt.IndexOf("=") != -1)
                txt = txt.Substring(txt.IndexOf("=") + 1);
            txt = txt.Replace("dayly", "day");
            txt = txt.Replace("qfqday", "day");
            return txt;
        }
        private void DownLoadsAllKdata(Button btn)
        {           
            Stocks _stocks = _jhcfg.Stocks;
            if (_stocks == null || _stocks.stocks.Count == 0)
                return;
            if (_stocks.Db == null) return;
            if (!_isrunning)
            {
                //_bshowtime = false;// checkBoxShowTimeOut.Checked;
                _isrunning = true;
                _completebtn = btn;
                _completebtn.Enabled = false;
                UpdateFin updatefin = new UpdateFin(_stocks);
                updatefin.SetCwfxType( true );
                updatefin.MaxThreadSum = 20;
                updatefin.ThreadShowMsg = new ShowDeleGate(form1.ThreadShowMsg);
                updatefin.ThreadCompleteRun = new CompleteDeleGate(form1.ThreadCompleteRun);
                ////qf.DealStocks.Add(_stocks.StockByIndex(2));
                ////qf.DealStocks.Add(_stocks.StockByIndex(3))
                //updatefin.DealStocks = _stocks.stocks;
                form1._updatetime = DateTime.Now;
                System.Threading.Thread nonParameterThread = new Thread(updatefin.DownLoadAllKData);
                nonParameterThread.Start();
            }
        }

        public void ExportKData(List<Stock> dealstock, StocksData stocksdata)
        {
            LocalKdTagstocks localkdtags = stocksdata.LocalkdTags;
            string str1 = "";
            try
            {
                foreach (Stock s in dealstock)
                {
                    LocalKdTagstock lt = localkdtags.Tag[s.ID];
                    if (lt != null && lt.kd != null)
                    {
                        str1 = string.Join("\r\n",
                            lt.Akd.Select(r =>
                            {
                                string sss = r.date + "\t" + r.open + "\t" + r.close + "\t" + r.high + "\t" + r.low + "\t" + r.vol + "\t" + r.reservation;
                                return sss;
                            }));
                    }
                    string savefilename = _jhcfg.Jsconfig.pathconfig.NowWorkPath() + "Export_" + stocksdata.KdataType + "_" + s.Code + ".txt";
                    str1 = "日期\tOPen\tClose\tHigh\tLow\tVol\tReservation\r\n" + str1;
                    MFile.WriteAllText(savefilename, str1);
                    ShowMsg("已保存到文件：" + savefilename);
                    
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show("保存失败,原因是：" + ee.Message);
            }
        }
        public void ExportFhKgData(List<Stock> dealstock )
        {

            FhsgDatas ls = JsonConvert.DeserializeObject<FhsgDatas>(File.ReadAllText(WorkPath + "AllFin.Dat"));
            try
            {
                foreach (Stock s in dealstock)
                {                  
                    FhsgStock find = ls.FhsgStocks.Find(r => r.stockcode == s.Code);
                    string str1 = "";
                    if(find!=null){
                        FhsgStock t = find;
                        if (t != null && t.FHSG != null)
                        {
                            str1 = string.Join("\r\n",
                               t.FHSG.Select( r => {
                                   string str = "";
                                   str = r.nd + "\t"+r.cqr+" "+r.FHcontent;
                                   return str;
                               }).ToList()
                                );
                        }
                        string savefilename = _jhcfg.Jsconfig.pathconfig.NowWorkPath() + "Export_FhKg_" + s.Code + ".txt";
                        MFile.WriteAllText(savefilename, str1);
                        ShowMsg("已保存到文件：" + savefilename);
                    }
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show("保存失败,原因是：" + ee.Message);
            }
        }
        public void ExportMacd(List<Stock> dealstock, StocksData stocksdata, bool OriginKdata = false )
        {
            LocalKdTagstocks localkdtags = stocksdata.LocalkdTags;
            try
            {
                foreach (Stock s in dealstock)
                {
                    List< KData> kd=null;
                    if (OriginKdata)
                    {
                        kd = s.GetKData().ToList();
                    }
                    else
                    {
                        LocalKdTagstock t = localkdtags.Tag[s.ID];
                        if (t != null)
                        {
                            kd = t.Akd;
                        }
                    }
                    if (kd != null)
                    {
                        string savefilename = _jhcfg.Jsconfig.pathconfig.NowWorkPath() + "Export_MACD_" + s.Code + ".txt";
                        MFile.WriteAllText(savefilename, s.OutMacd( kd));
                        ShowMsg("已保存到文件：" + savefilename);
                    }
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show("保存失败,原因是：" + ee.Message);
            }
        }
        public void CreateAllMacd(StocksData stocksdata)
        {
            LocalKdTagstocks localkdtags = stocksdata.LocalkdTags;
            NetObjectTagstock[] Tag = new NetObjectTagstock[2000];
	        for (int i = 0; i < 2000; i++)
	            Tag[i] = new NetObjectTagstock();
	        foreach (Stock s in _stocks.stocks)
	            Tag[s.ID].Init(s);
            SaveJsonTag savetag = new SaveJsonTag(System.DateTime.Now, Tag);
            foreach (Stock s in _stocks.stocks)
            {
                LocalKdTagstock t = localkdtags.Tag[s.ID];
                if (t != null && t.kd != null)
                {
                    Tag[s.ID].ObjTag = MACD.ComputeMacdArray(t.Akd.ToArray());
                }
            }
            string savefilename = WorkPath + stocksdata.KdataType + "_AllMacd.dat";
            savetag.Save(savefilename);
            ShowMsg("已保存到文件：" + savefilename);
        }
        public void ExportTestKData(List<Stock> dealstock,StocksData stocksdata, bool ComputeVol,bool bCrossKdata,int daylydays)
        {
            TestStocks ts = new TestStocks(_jhcfg, _jhcfg.ActiveStocksData);
            LocalKdTagstocks localkdtags = stocksdata.LocalkdTags;
            StringBuilder sb = new StringBuilder();
            foreach(Stock s in dealstock)
            {
            //    TestStockSelect(Stock s, bool ComputeVol, bool bCrossKdata,bool bMonitOnedays=false,
            //bool DebugOutPut = false, int staticdaylenght = 200, bool FromParentCmd = false, int daylydays = 0)
                sb.AppendLine(
                ts.TestStockSelect(s,ComputeVol, bCrossKdata, false,
                  false, 200, true, daylydays));
            }
            string SLinfor = ts.TestStockSelect(null,ComputeVol, bCrossKdata, false,
                  false, 200, true, daylydays,true);
            
            string pathname = _jhcfg.Jsconfig.pathconfig.NowWorkPath() + "Export_" + stocksdata.KdataType;
            if (ComputeVol)
                pathname += "_Vol";
            else
                pathname += "_Price";
            if (bCrossKdata)
                pathname += "_CrossKdata";          
            string savefilename = pathname + SLinfor +"_" + dealstock.Count+ ".txt";
            MFile.WriteAllText(savefilename, sb.ToString());
            ShowMsg("已保存到文件：" + savefilename);
        }
        public static string  ExportCW(string ChineseName, string propertyname, List<Stock> list,Stocks stocks, bool reportbyyears)
        {
            string Msg = "";
            string datatype = "reports";
            if (reportbyyears)
                datatype = "years";
            List<Stock> DealStocks = list;
            if (list.Count == 0)
                DealStocks = new List<Stock>(stocks.stocks);
            Type type = typeof(JsonMainCWFX);
            PropertyInfo property = type.GetProperty(propertyname);
            if (property == null) MessageBox.Show("找不到属性名称"); ;
            StringBuilder sb = new StringBuilder();
            try
            {
                foreach (Stock s in DealStocks)
                {
                    sb.Append(s.Name + "\t" + s.Code + "\t");
                    NetObjectTagstock t = stocks.GetTagstock(s.ID);
                    if (t != null && t.ObjTag != null)
                    {
                        List<JsonMainCWFX> ls = JsonConvert.DeserializeObject<List<JsonMainCWFX>>(t.ObjTag.ToString());
                        sb.AppendLine(string.Join("\t", ls.Select(rr =>
                        {
                            object o = property.GetValue(rr, null);
                            if (o == null)
                                return rr.date + "\t" + string.Empty;
                            return rr.date + "\t" + o.ToString();
                        }).ToList()));
                    }
                }
                string savefilename = stocks.Pathconfig.NowWorkPath() + "Export_" + datatype + ChineseName + ".txt";
                MFile.WriteAllText(savefilename, sb.ToString());
                Msg = "已保存到文件：" + savefilename;
            }
            catch (Exception ee)
            {
                Msg = "保存失败,原因是：" + ee.Message;
            }
            return Msg;
        }

        private string WorkPath { get { return _jhcfg.Jsconfig.pathconfig.WorkPath; } }
    }    
}
